package com.lzh.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName FeignConfig
 * @Description TODO
 * @Author liuzhihui
 * @Date 2020/9/4 15:29
 * @Version 1.0
 **/
@Configuration
public class FeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //1.RequestContextHolder拿到当前请求的数据，相当与拿到controller入参的HttpServletRequest
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

                if (requestAttributes!=null){
                    //老请求
                    HttpServletRequest request = requestAttributes.getRequest();

                    if (request!=null){
                        //2.同步请求头信息->cookie
                        String cookie = request.getHeader("Cookie");
                        requestTemplate.header("Cookie",cookie);
                    }
                }
            }
        };
    }
}
